package mina;
import java.awt.image.BufferedImage;
import java.net.*;
import java.io.*;
import java.sql.*;
import java.util.Random;
import java.util.Scanner;

import javax.imageio.ImageIO;
import javax.naming.Context;
//import android.content.Context;
//import android.net.DhcpInfo;
//import android.net.wifi.WifiInfo;
//import android.net.wifi.WifiManager;
//import android.net.Network;
//import android.net.ConnectivityManager;
//import android.net.NetworkCapabilities;
//import android.net.NetworkInfo;
//import android.os.Build;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.Enumeration;

public class TcpServer {
//    private static final String TAG = "MainActivity";
//    public static void main(String[] args)throws Exception{
//        try{
//            //建立服务器套接字
//            System.out.println("等待连接...");
//            ServerSocket sever = new ServerSocket(8082);//7890
//            //监听
//            System.out.println("监听...");
//            Socket socket = sever.accept();
//            //建立连接
//            System.out.println("建立连接");
//            InputStreamReader Sysin = new InputStreamReader(System.in);  //键盘输入
//            BufferedReader SysBuf = new BufferedReader(Sysin);   //键盘键入的内容放入缓冲区
//
//            InputStreamReader Socin = new InputStreamReader(socket.getInputStream());  //从socket 读取
//            BufferedReader SocBuf = new BufferedReader(Socin);
//            //建立输出流
//            System.out.println("建立输出流");
//            PrintWriter Socout = new PrintWriter(socket.getOutputStream());   //数据写入socket
//            System.out.println("socket连接成功");
////            Log.v(TAG,"socket连接成功");
//
//            //读取客户端发来的消息
//            String sql3 = SocBuf.readLine();
//            System.out.println("客户端发来:"+sql3);//读到客户端发来的消息打印
//            String ResultSend = MyTest(sql3);  //查询到的结果
//            while (!ResultSend.equals("bye"))//   发送的消息不为 bye
//            {
//                Socout.println(ResultSend);        //向socket发送数据
//                Socout.flush();       //让客户端马上接收到发送的内容
//                System.out.println("向socket发送:"+ResultSend);//打印出来
//
//                String rl = SocBuf.readLine();    //客户端发来的消息rl
//                if(!rl.equals("ok"))
//                    System.out.println("Client:"+rl);   //发来的不是ok就打印
//                else
//                    break;
//                ResultSend = MyTest(rl);    //查询
//            }
//            //关闭IO和Socket
//            Socout.close();
//            Socin.close();
//            sever.close();
//
//        }catch (Exception e){
//            System.out.println("Error"+e);
//        }
//    }

//    public static void main(String[] args) {
//        while (true){
//        try (ServerSocket serverSocket = new ServerSocket(8082)) {
//            System.out.println("等待连接...");
//
//            try (Socket socket = serverSocket.accept()) {
//                System.out.println("建立连接");
//                try (InputStreamReader socIn = new InputStreamReader(socket.getInputStream());
//                     BufferedReader socBuf = new BufferedReader(socIn);
//                     PrintWriter socOut = new PrintWriter(socket.getOutputStream(), true);
//                     InputStreamReader sysIn = new InputStreamReader(System.in);
//                     BufferedReader sysBuf = new BufferedReader(sysIn)) {
//
//                    System.out.println("建立输出流");
//                    System.out.println("socket连接成功");
//
//                    String sql3 = socBuf.readLine();
//                    System.out.println("客户端发来:" + sql3);
////                    String resultSend = MyTest(sql3);
//
////                    while (!resultSend.equals("bye")) {
////                        socOut.println(resultSend);
////                        System.out.println("向socket发送:" + resultSend);
////                        String rl = socBuf.readLine();
////                        if (!rl.equals("ok")) {
////                            System.out.println("Client:" + rl);
////                        } else {
////                            break;
////                        }
////                        resultSend = MyTest(rl);
////                    }
//                }
//            }
//
//        } catch (Exception e) {
//            System.err.println("Error: " + e.getMessage());
//            e.printStackTrace();
//        }
//        }
//    }

// 获取本机IP地址的简化方法
//
 //读取文字。。
//public static void main(String[] args) {
//        int port = 8082;
//        try (ServerSocket serverSocket = new ServerSocket(port)) {
//            System.out.println("等待连接...");
//
//            try (Socket socket = serverSocket.accept()) {
//                System.out.println("建立连接");
//                //
//                try (InputStreamReader socIn = new InputStreamReader(socket.getInputStream());
//                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//
//                     BufferedReader socBuf = new BufferedReader(socIn);
//                     PrintWriter socOut = new PrintWriter(socket.getOutputStream(), true);
//                     InputStreamReader sysIn = new InputStreamReader(System.in);
//                     BufferedReader sysBuf = new BufferedReader(sysIn)
//                     ) {
//                     System.out.println("建立输出流");
//                    System.out.println("socket连接成功");
//                    socOut.println("成功连接到: " + port);
//                    while (true) {
//                        try {
//                            // 1.从socket读取文字消息
//                            String message = socBuf.readLine();
//                            System.out.println("收到消息: " + message);
//
//                            if (message == null) {
//                                System.err.println("对方关闭了连接");
//                                break; // 直接退出循环
//                            }
//                            if (message.equals("null")) {
//                                System.out.println("收到空消息");
//                                continue; // 跳过当前循环，继续等待新消息
//                            }
//
//
//                            // 处理消息并发送响应
////                            socOut.println("已收到消息: " + message);
//                        } catch (SocketException e) {
//                            System.err.println("连接重置: " + e.getMessage());
//                            break;
//                        } catch (IOException e) {
//                            System.err.println("IO异常: " + e.getMessage());
//                            break;
//                        }  finally {
//                                try {
//                                    socOut.close();
//                                    socBuf.close();
//                                    socket.close();
//                                } catch (IOException e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                    }
//                }
//            } catch (Exception e) {
//                System.out.println("socket连接失败");
//
////                socOut.println("未连接到: " + port);
//                System.err.println("Error: " + e.getMessage());
//                e.printStackTrace();
//            }
//        } catch (Exception e) {
//            System.err.println("Error: " + e.getMessage());
//            e.printStackTrace();
//        }
//}

//只能接收一次图片
//public static void main(String[] args) {
//    int port = 8082;
//    try (ServerSocket serverSocket = new ServerSocket(port)) {
//        System.out.println("等待连接...");
//
//        try (Socket socket = serverSocket.accept()) {
//            System.out.println("建立连接");
//            try (InputStream in = socket.getInputStream();
//                 FileOutputStream out = new FileOutputStream("received_image.jpg")) {
//                System.out.println("建立输出流");
//                System.out.println("socket连接成功");
//
//                byte[] buffer = new byte[8192]; // 8KB 缓冲区
//                int bytesRead;
//                while ((bytesRead = in.read(buffer)) != -1) {
//                    out.write(buffer, 0, bytesRead);
//                }
//
//                // 数据接收完成后，尝试读取并保存图片
//                try (FileInputStream fis = new FileInputStream("received_image.jpg");
//                     ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
//                    byte[] fileBuffer = new byte[8192];
//                    while ((bytesRead = fis.read(fileBuffer)) != -1) {
//                        baos.write(fileBuffer, 0, bytesRead);
//                    }
//
//                    byte[] imageBytes = baos.toByteArray();
//                    try {
//                        BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
//                        if (image != null) {
//                            File outputFile = new File("D:\\Androp\\Camera-main\\d7de4-main\\2.0\\release\\output.jpg");
//                            ImageIO.write(image, "jpg", outputFile);
//                            System.out.println("图片已保存到: " + outputFile.getAbsolutePath());
//                        } else {
//                            System.out.println("接收到的数据不是有效的图片");
//                        }
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            } catch (SocketException e) {
//                System.err.println("连接重置: " + e.getMessage());
//            } catch (IOException e) {
//                System.err.println("IO异常: " + e.getMessage());
//            }
//        } catch (Exception e) {
//            System.out.println("socket连接失败");
//            System.err.println("Error: " + e.getMessage());
//            e.printStackTrace();
//        }
//    } catch (Exception e) {
//        System.err.println("Error: " + e.getMessage());
//        e.printStackTrace();
//    }
//}

//接收多张图片
public static void main(String[] args) {
    int port = 8082;
    try (ServerSocket serverSocket = new ServerSocket(port)) {
        System.out.println("等待连接...");

        while (true) { // 外层循环，用于接受多个客户端连接
            try (Socket socket = serverSocket.accept()) {
                System.out.println("建立连接");

                InputStream in = socket.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                int bytesRead;

                // 内层循环，用于接收单张图片的数据
                while ((bytesRead = in.read(buffer)) != -1) {
                    baos.write(buffer, 0, bytesRead);
                }

                // 将接收到的数据转换为字节数组
                byte[] imageBytes = baos.toByteArray();

                Random random = new Random();
                String fileName = "D:\\Androp\\Camera-main\\d7de4-main\\2.0\\release\\output" + random.nextInt(1000) + ".jpg";

                // 保存图片到文件
                try (FileOutputStream out = new FileOutputStream(fileName)) {
                    out.write(imageBytes);
                    System.out.println("图片已保存");
                }

                // 关闭资源
                in.close();
            } catch (SocketException e) {
                System.err.println("连接重置: " + e.getMessage());
            } catch (IOException e) {
                System.err.println("IO异常: " + e.getMessage());
            }
        }
    } catch (Exception e) {
        System.out.println("服务器socket连接失败");
        System.err.println("Error: " + e.getMessage());
        e.printStackTrace();
    }
}

    // 验证字节数组是否为有效图片
    public static boolean isValidImage(byte[] bytes) {
        if (bytes == null || bytes.length < 8) {
            return false;
        }

        // 检查JPEG文件头
        if (bytes[0] == (byte)0xFF && bytes[1] == (byte)0xD8 && bytes[2] == (byte)0xFF) {
            return true;
        }

        // 检查PNG文件头
        if (bytes[0] == (byte)0x89 && bytes[1] == (byte)0x50 && bytes[2] == (byte)0x4E
                && bytes[3] == (byte)0x47 && bytes[4] == (byte)0x0D && bytes[5] == (byte)0x0A
                && bytes[6] == (byte)0x1A && bytes[7] == (byte)0x0A) {
            return true;
        }

        // 检查GIF文件头
        if (bytes[0] == 'G' && bytes[1] == 'I' && bytes[2] == 'F') {
            return true;
        }

        return false;
    }

//    public static String MyTest(String sql1) throws ClassNotFoundException, SQLException {
//        //添加驱动
//        Class.forName("com.mysql.jdbc.Driver");
//        String url = "jdbc:mysql://localhost:3306/opc?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true";
//        String user = "root";
//        String password = "root"; // 用户名和密码；
//        Connection connection = DriverManager.getConnection(url, user, password);//获取连接对象
//
//        //String[][] res = new String[99][99];
//        String res = null;
//        if (connection == null) {
//            System.out.println("连接失败");
//        } else {
//            //System.out.println("数据库连接成功");
//            Statement stmt = connection.createStatement();
//            ResultSet resultSet = stmt.executeQuery(sql1);//查的语句
//            while (resultSet.next()) {
//                 res = resultSet.getString("prod_name");
//            }
//        }
//        return res;
//    }
}
